//
//  DSMoreViewController.m
//  DS爱信
//
//  Created by 秦建英 on 14-5-27.
//  Copyright (c) 2014年 秦建英. All rights reserved.
//

#import "DSMoreViewController.h"
#import "DSRachViewController.h"
#import "DSLgViewController.h"
#import "NetAccess.h"
#import "Header.h"
@interface DSMoreViewController ()<UIAlertViewDelegate,NSURLConnectionDataDelegate>
@end
@implementation DSMoreViewController
#define APP_YES @"http://182.92.157.109/api/agent/clientinfo?userid=2&os=2"
#define APP_DownloadURL @"最新版本号为:1.1"
{
    NSUserDefaults *users;
    NSMutableData *_data;
    NSString *_string;
    UILabel *_label;
    UILabel *_label1;
    UILabel *_label2;
    NSString *_word;
    UIAlertView *_alertView;
    UIImageView *image4;
    NSString *_name;
    int currentVersion;
    NSString *_Version;
    NSString *_urlt;
    NetAccess *_net;
    MBProgressHUD* pro;
    UIImageView *_imageViews;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}
-(void)match
{
    pro = [[MBProgressHUD alloc] initWithView:self.view];
    pro.labelText = @"请稍后..";
    pro.mode = MBProgressHUDModeText;
    [self.view addSubview:pro];
    [pro showAnimated:YES whileExecutingBlock:^{
        [NSThread sleepForTimeInterval:20.0];
    } completionBlock:^{
    }]; 
}
-(void)tabHead
{
    _imageViews =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"df.png"]];
    _imageViews.frame =CGRectMake(0, 0, DeviceWidth, 64);
    UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(0, 25, _imageViews.frame.size.width, 30)];
    label.text=@"个人中心";
    label.textColor=[UIColor yellowColor];
    label.backgroundColor =[UIColor clearColor];
    label.textAlignment =NSTextAlignmentCenter;
    [_imageViews addSubview:label];
    [self.view addSubview:_imageViews];
}
#pragma mark--网络代理方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _data =[[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    _string =[[NSString alloc]initWithData:_data encoding:NSUTF8StringEncoding];
    NSLog(@"即将跳转  %@",_string);
    if([_string hasPrefix:@"0|1"])
    {[pro removeFromSuperview];
        NSArray *listItems = [_string componentsSeparatedByString:@"|"];
        _label1.text =[NSString stringWithFormat:@"话费余额:  %@元",[listItems objectAtIndex:2]];
        _label2.text =[NSString stringWithFormat:@"有效期:  %@",[listItems objectAtIndex:3]];
        _alertView = [[UIAlertView alloc] initWithTitle:_label1.text message:_label2.text delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [_alertView show];
    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_alertView removeFromSuperview];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self tabHead];
    UIBarButtonItem *bii =[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"tab_3.png"] style:UIBarButtonItemStylePlain target:self action:@selector(bbiClick)];
    self.navigationItem .rightBarButtonItem =bii;
    [self infoning];
    _net = [NetAccess sharedNetAccess];
}
-(void)bbiClick
{UIAlertView *v =[[UIAlertView alloc] initWithTitle:@"关于"message:@"惠话 v2.1" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [v show];
}
-(void)infoning
{
    users =[NSUserDefaults standardUserDefaults];
    NSArray *array =[users objectForKey:@"users"];
    NSDictionary *dict =[array objectAtIndex:0];
    _name =[dict objectForKey:@"userword"];
    _word =[dict objectForKey:@"username"];
    
    UILabel *labn =[[UILabel alloc]initWithFrame:CGRectMake(image4.frame.origin.x+102, _imageViews.frame.origin.y+120, 320-image4.frame.origin.x+40, 30)];
    labn.text =[NSString stringWithFormat:@"登录号码为:%@",_word];
    [self.view addSubview:labn];
    _label =[[UILabel alloc]init];
    _label1 =[[UILabel alloc]init];
    _label2 =[[UILabel alloc]init];
#pragma mark===switch
    
    NSMutableArray *arraty =[[NSMutableArray alloc]initWithObjects:@"手机充值",@"余额查询",@"资费说明",@"版本升级",@"客服电话",@"注销账号", nil];
    NSMutableArray *sdt =[[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:@"充值 (2).png"],[UIImage imageNamed:@"关于.png"],[UIImage imageNamed:@"查询.png"],[UIImage imageNamed:@"升级.png"],[UIImage imageNamed:@"资费.png"],[UIImage imageNamed:@"注销.png"], nil];
    for(int j=0;j<3;j++)
    {
        UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
        UILabel *xm =[[UILabel alloc]initWithFrame:CGRectMake(17+100*j, 260+btn.frame.size.height, 90, 40)];
        btn.layer.cornerRadius =10;
        btn.tag =10+j;
        btn.frame =CGRectMake(15+100*j, _imageViews.frame.origin.y+200, 70, 60);
        xm.text =[NSString stringWithFormat:@"%@",[arraty objectAtIndex:j]];
        [btn setImage:[sdt objectAtIndex:j] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        [self .view addSubview:xm];
    }
    for(int j=0;j<3;j++)
    {
        UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
        UILabel *xm =[[UILabel alloc]initWithFrame:CGRectMake(17+100*j, 360+btn.frame.size.height, 90, 40)];
        btn.layer.cornerRadius =10;
        btn.tag =13+j;
        btn.frame =CGRectMake(15+100*j, 300, 70, 60);
        xm.text =[NSString stringWithFormat:@"%@",[arraty objectAtIndex:j+3]];
        [btn setImage:[sdt objectAtIndex:j+3] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        [self .view addSubview:xm];
        
        image4=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"call_living_p@2x.jpg"]];
        image4.frame =CGRectMake(10,_imageViews.frame.size.height+20 ,90, 90);
        [self.view addSubview:image4];
        self.view.backgroundColor =[UIColor whiteColor];
    }
}
-(void)btnClick:(UIButton *)bbt
{
    NSString *title =@"资费说明";
    NSString *message =@"资费： 0.1元/分钟";
    _alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
    if(bbt.tag ==10)
    {
        DSRachViewController *rach =[[DSRachViewController alloc]init];
        UINavigationController *nvc =[[UINavigationController alloc]initWithRootViewController:rach];
        [self presentViewController:nvc animated:YES completion:^{
        }];
    }
    if(bbt.tag ==11)
    {[self match];
        if(![_net haveNet])
        {
            NSLog(@"网络不可用");
            //没有网络
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];[pro removeFromSuperview];
        }
        else{
            [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(getStarte:) object:nil];
            [self performSelector:@selector(getStarte:) withObject:nil afterDelay:0.5f];
        }
    }
    if(bbt.tag ==12)
    {
        [_alertView show];
    }
    if(bbt.tag ==13)
    {[self match];
        if(![_net haveNet])
        {[pro removeFromSuperview];
            NSLog(@"网络不可用");
            //没有网络
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }else{
            [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(getNewVersion:) object:nil];
            [self performSelector:@selector(getNewVersion:) withObject:nil afterDelay:0.5f];
        }
    }
    if(bbt.tag ==14)
    {
        UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"客服电话"message:@"18653121659" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"马上拨打",nil];
        av.tag =1001;
        [av show];
    }
    if(bbt.tag ==15)
    {
        [users removeObjectForKey:@"users"];
        [users synchronize];
        if(IOS5==YES)
        {
            [self presentViewController:[DSLgViewController alloc] animated:YES completion:^{
            }];
        }
        else
        {
            NSString *title =@"提示";
            _alertView.title =title;
            NSString *message=@"注销成功，正在退出程序，请稍后....";
            _alertView.message =message;
            [_alertView show];
            [self presentViewController:[DSLgViewController alloc] animated:YES completion:^{
                sleep(3);
            }];
            
        }
    }
}
-(void)getStarte:(id)sender
{
    NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"http://182.92.157.109/api/mapp/login.aspx?a=%@&b=%@",_word,_name]];
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
    NSURLConnection *connent =[[NSURLConnection alloc]initWithRequest:request delegate:self];
    [connent start];
}
- (void)getNewVersion:(id)sender
{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:APP_YES]];
    NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    _Version =[dict objectForKey:@"VersionNumber"];
    _urlt =[dict objectForKey:@"Url"];
    currentVersion=[_Version intValue];
    [self checkUpdate];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if(alertView.tag ==1000)
    {
        if (buttonIndex != [alertView cancelButtonIndex])
        {
            NSURL *url = [NSURL URLWithString:_urlt];
            [[UIApplication sharedApplication] openURL:url];
        }
    }
    if(alertView.tag ==1001)
    {
        if(buttonIndex==1)
        {
            NSString *phone =alertView.message;// 电话号码
            NSString *phoneNum =[phone stringByReplacingOccurrencesOfString:@"-" withString:@""];
            NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phoneNum]];
            NSLog(@"%@",phoneURL);
            [[UIApplication sharedApplication]openURL:phoneURL];
        }
    }
}
-(void)checkUpdate
{[pro removeFromSuperview];
    NSString * sLastVersion=@"1.1";//取最新的版本自己去实现
    if (![sLastVersion isEqualToString:_Version])
    {
        NSLog(@"更新");
        UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"升级提示"message:APP_DownloadURL delegate:self cancelButtonTitle:@"以后再说" otherButtonTitles:@"马上更新",nil];
        av.tag =1000;
        [av show];
    }
    else
    {
        UIAlertView *v =[[UIAlertView alloc] initWithTitle:@"升级提示"message:@"已是最新的版本，无需下载" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [v show];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end
